package com.summer.order.controller;

import java.sql.CallableStatement;
import java.sql.Connection;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Date;
import java.util.List;

import javax.annotation.Resource;

import org.hibernate.HibernateException;
import org.hibernate.Session;
import org.springframework.context.annotation.Scope;
import org.springframework.dao.DataAccessException;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.summer.core.annotations.ScopeType;
import com.summer.core.controller.EntityQuery;
import com.summer.core.util.FacesUtil;
import com.summer.core.util.IdGenerator;
import com.summer.order.model.Cookbook;
import com.summer.order.model.DayFood;
import com.summer.order.model.OrderDetail;
import com.summer.order.model.ReportOrder;
import com.summer.order.model.UserDayFood;
import com.summer.order.model.UserOrder;
import com.summer.order.service.UserOrderService;
import com.summer.order.util.OrderConstants;
import com.summer.user.model.User;

@Component
@Scope(ScopeType.VIEW)
public class UserOrderList extends EntityQuery<UserOrder> {

	private final String HQL = "select userOrder from UserOrder userOrder";
	private final String COUNT_HQL = "select count(userOrder) from UserOrder userOrder";
	
	@Resource
	UserOrderService userOrderService;
	
	private Date startDate;
	
	private Date endDate;
	
	private String dateBetween;
	
	private String cookbook_id;
	
	public DateFormat df = new SimpleDateFormat("yyyyMMdd");

	public UserOrderList() {

		setCountHql(COUNT_HQL);
		setHql(HQL);
		final String[] RESTRICTIONS = {

				"userOrder.id=#{userOrderList.example.id}",
				"userOrder.cookbook_id like #{userOrderList.cookbook_id}",
				"userOrder.user.id like #{userOrderList.example.user.id}",
				"userOrder.user.realname like #{userOrderList.example.user.realname}",
				"userOrder.dateBetween like #{userOrderList.dateBetween}"

		};
		setRestrictionExpressionStrings(Arrays.asList(RESTRICTIONS));
	}
	
	@Override
	protected void initExample() {
		UserOrder example = new UserOrder();
		User user = new User();
		example.setUser(user);
		setExample(example);
		
	}

	
	public ReportOrder getReportOrder() {
		if((startDate == null || endDate == null) && cookbook_id == null) {
			return null;
		}
		List<UserOrder> userOrderList = getHt().find("from UserOrder uo where uo.dateBetween = ? or uo.cookbook_id = ?",dateBetween , cookbook_id);
		return userOrderService.getReportOrder(userOrderList);
	}
	

	@Transactional(readOnly = false , rollbackFor = Exception.class)
	public void checkOut() {
		try {
			DateFormat df = new SimpleDateFormat("yyyyMMdd");
			if(startDate == null || endDate == null) {
				FacesUtil.addErrorMessage("先选上要结算的那个菜单的时间区间呗，要不我也不知道你要结算哪个");
				return ;
			}
			String cookbook_id = df.format(startDate)+df.format(endDate);
			List<Cookbook> cookbookList = getHt().find("select cookbook from Cookbook cookbook where cookbook.id=?",cookbook_id);
			if(cookbookList == null || cookbookList.size() == 0) {
				FacesUtil.addErrorMessage("你选这日子也没有菜单啊，你自己瞅瞅去吧");
				return;
			}
			
			Cookbook cookbook = cookbookList.get(0);
			if(cookbook.getStatus()== OrderConstants.CookbookStatus.DISABLE) {
				FacesUtil.addErrorMessage("这菜单你都结算完了，别再结算了一遍哦~");
				return;
			}
			cookbook.setStatus(OrderConstants.CookbookStatus.DISABLE);
			
			List<UserOrder> userOrderList = getHt().find("from UserOrder u where u.cookbook_id=?",cookbook.getId());
			List<DayFood> dayFoodList = getHt().find("from DayFood df where df.cookbook.id=?",cookbook.getId());
			
			if(userOrderList != null && userOrderList.size() > 0) {
				
				for (UserOrder userOrder : userOrderList) {
					OrderDetail orderDetail = new OrderDetail();
					orderDetail.setId(IdGenerator.randomUUID());
					orderDetail.setUserOrder(userOrder);
					orderDetail.setUser(userOrder.getUser());
					StringBuffer breakfastDetail = new StringBuffer();
					StringBuffer lunchDetail = new StringBuffer();
					
					List<UserDayFood> userDayFoodList = getHt().find("select userDayFood from UserDayFood userDayFood where userDayFood.userOrder.id=? order by userDayFood.date asc",userOrder.getId());
					if(userDayFoodList != null && userDayFoodList.size() > 0) {
						for (UserDayFood userDayFood : userDayFoodList) {
							if(userDayFood.getBreakfast().equals("yes")) {
								breakfastDetail.append(new SimpleDateFormat("yyyyMMdd").format(userDayFood.getDate())+",");
							}
							if(userDayFood.getLunch().equals("yes")) {
								lunchDetail.append(new SimpleDateFormat("yyyyMMdd").format(userDayFood.getDate())+",");
							}
						}
					}
					System.out.println(breakfastDetail.toString());
					orderDetail.setCookbook(cookbook);
					orderDetail.setBreakfastDetail(breakfastDetail.toString() != null && !breakfastDetail.toString().equals("") ? breakfastDetail.toString().trim().substring(0,breakfastDetail.length()-1) : "");
					orderDetail.setLunchDetail(lunchDetail.toString() != null && !lunchDetail.toString().equals("") ? lunchDetail.toString().trim().substring(0,lunchDetail.length()-1) : "");
					
					getHt().save(orderDetail);
				}
			}
			getHt().merge(cookbook);
			summaryCheck(cookbook.getId());
		} catch (DataAccessException e) {
			FacesUtil.addErrorMessage("啊哦，结算失败了，快看看后台");
			e.printStackTrace();
		} catch (Exception e) {
			FacesUtil.addErrorMessage("啊哦，结算失败了，快看看后台");
			e.printStackTrace();
		}
		FacesUtil.addInfoMessage("yeah!结算完成了！");
		
	}
	
	
	@Transactional(readOnly = false, rollbackFor = Exception.class)
	public void summaryCheck(String cookbook_id) {

		Session session = getHt().getSessionFactory().getCurrentSession();
		Connection conn = session.connection();
		CallableStatement call;
		try {
			call = conn.prepareCall("{call p_order_summary(?)}");// 调用存储过程
			call.setString(1, cookbook_id);
			call.execute();// 执行存储过程
		} catch (HibernateException e) {
			FacesUtil.addInfoMessage("结算失败了，去瞅瞅后台报啥错了！");
			e.printStackTrace();
		} catch (SQLException e) {
			FacesUtil.addInfoMessage("结算失败了，去瞅瞅后台报啥错了！");
			e.printStackTrace();
		}
	}
	
	public void orderDetail() {
		
	}
	
	
	
	public Date getStartDate() {
		return startDate;
	}

	public void setStartDate(Date startDate) {
		this.startDate = startDate;
	}

	public Date getEndDate() {
		return endDate;
	}

	public void setEndDate(Date endDate) {
		this.endDate = endDate;
	}

	public String getDateBetween() {
		
		DateFormat df =  new SimpleDateFormat("yyyyMMdd");
		if(startDate != null && endDate != null) {
			dateBetween = df.format(startDate) + "-" + df.format(endDate);
		}
		System.out.println(dateBetween);
		return dateBetween;
	}

	public void setDateBetween(String dateBetween) {
		this.dateBetween = dateBetween;
	}

	public String getCookbook_id() {
		return cookbook_id;
	}

	public void setCookbook_id(String cookbook_id) {
		this.cookbook_id = cookbook_id;
	}
	
	
	
	
	

}
